﻿import XOrules
import XOdata
from platform.GameManager import GameManager
from platform.KA import KA

from platform.jutils import *
from platform.utilits import *

super = GameManager

class XOGameManager(GameManager):
	def __init__(this, bgtp_mail_):
		this.bgtp_mail = bgtp_mail_;
		this.name = USR_GAMEMANAGER;
		this.client = false;
		this.gameName = "XO";
		this.data = XOdata.XOdata();
		GameManager.__init__(this);		
		super.setState(this, GM_SETTINGS);

	
	#add gamer
	def pre_addGamer(this, req):
		if (this.data.gamers.count(req.usr) != 0):
			return "this player here";
	
	def addGamer(this, req):
		this.data.gamers.append(req.usr);
	
	def post_addGamer(this, req):
		this.sendRequest(req);
	
	#remove gamer
	def pre_removeGamer(this, req):
		if (this.data.gamers.count(req.usr) == 0):
			return "no this gamer";
	
	def removeGamer(this, req):
		this.data.gamers.remove(req.usr);	
	
	def post_removeGamer(this, req):
		this.sendRequest(req);
	
	#setGamerParty
	def pre_setGamerParty(this, req):
		if (this.data.gamers.count(req.usr) == 0):
			return "no this gamer";
		if (this.data.partyes.keys().count(req.body["PARTY"]) == 0):
			return "no this party:" + req.body;
	
	def setGamerParty(this, req):
		this.data.partyes[req.body["PARTY"]] = req.usr;
	
	def post_setGamerParty(this, req):
		this.sendRequest(req);
	
	#createAI
	def pre_createAI(this, req):
		pass
	
	def createAI(this, req):
		#def _createAI():
		#	import os; os.system('python XO\AIclient.py')
		#import thread; thread.start_new_thread(_createAI, ())		
		import os; os.startfile("..\games\XO\AI\AIclient.py");
		
	def post_createAI(this, req):
		pass
	
	#start game
	def pre_startGame(this, req):
		if (this.data.partyes[XOrules.Xchar] == null or this.data.partyes[XOrules.Ochar] == null):
			return "need two players";
	
	def startGame(this, req):
		this.data.fld = XOrules.createField(this.data.size);
		this.data.who = XOrules.whoseTurn(this.data.fld);
		super.setState(this, GM_GAME);
	
	def post_startGame(this, req):
		this.sendRequest(req);	
	
	#make turn
	def _isItWin(this):
		whoseWin_ = XOrules.whoseWin(this.data.fld, this.data.minChain);
		return not (whoseWin_ == XOrules.Fchar) and not (whoseWin_ == XOrules.NBchar);
	
	def pre_makeTurn(this, req):
		if (this.data.partyes.get(this.data.who) != req.usr):
			return "it is not your turn";
		if (this._isItWin()):
			return "the game is over";
		if (not XOrules.isItTurn(this.data.fld, this.data.who, (req.body["X"], req.body["Y"]))):
			return "it is not avalibale turn";
	
	def makeTurn(this, req):
		XOrules.makeTurn(this.data.fld, this.data.who, (req.body["X"], req.body["Y"]));
		if (this._isItWin()):
			this.stopGame();	
		else:
			if this.data.who == XOrules.Xchar:
				this.data.who = XOrules.Ochar;
			else:	
				this.data.who = XOrules.Xchar;
	
	def post_makeTurn(this, req):
		this.sendRequest(req);
		

